<template>
    <view class="box">
        <!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<view @click="selected==1?false:dialog = true">{{userName || '会员：'}}</view>
				<view style="position: relative;">{{start_date || '日期：'}}
					<picker mode="date" :disabled="selected==1" :start="start" :end="end"  @change="bindDateChange" style="position: absolute;left:0;top: 0;width: 100%;height: 100%;">
						<view class="date">{{start_date}}</view>
					</picker> 
				</view>
			</view>
			<view class="save" @click="showModalbtn(1)" v-if="!selected">保存</view>
			<view class="toSend" @click="showModalbtn(3)">生成评估</view>
		</view>

        <view class="content">
            <view class="question" v-for="(item,index) in questionnaire" :key="index">
				<view class="title">
					<text>{{index <= 8 ? '0'+(index+1) : index+1}}</text>
					<view>{{item.name}}</view>
				</view>
				<view class="option" v-for="(aitem,aindex) in item.adTopicsRepliesEntityList" :key="aindex">
					<view @click="answer(aitem,item)"><text>{{aitem.elections}}、{{aitem.value}}</text> 
						<image src="@/static/img/select@2x.png" v-if="aitem.checked == false"></image>  
						<image src="@/static/img/selected@2x.png" v-else></image>
					</view>
				</view>
			</view>
        </view>
		<!-- 会员弹框 -->
		<member :dialog.sync="dialog"  @hidedialog="hidedialog" @chooseUser="chooseUser"></member>
		<u-modal v-model="showModal1" :show-cancel-button="true" @confirm="Modalconfirm" :content="showContent"></u-modal>
		
		<reportImgType2 ref="reportImgType2" :info="info"></reportImgType2>
		
    </view>
</template>
<script>
	import { getUrlParam } from '@/static/js/filter.js';
	import reportImgType2 from '@/pages/quickly/healthStatus/reportImgType2.vue'
	import member  from '@/components/selectMember/selectMember.vue';
	export default{
		components:{member,reportImgType2},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				questionnaire:[],
				showModal: false,
				showContent: '',
				dialog: false,
				id: '',
				userName:'',
				start: '',
				end: currentDate,
				start_date:'',
				showModal1: false, //选择日期弹框组件
				info:{},
				selected:'',
				isSave : false
			}
		},
		onLoad(options) {
			const _this = this;
			_this.findByTopicsTypeAxios().then((response)=>{
				if(options.edit == 1 || options.selected == 1){
					_this.selected = options.selected;
					_this.edit = true;
					_this.editId = options.id 
					_this.$api.healthAssessmentDetails(options.id).then((res)=>{
						const data = res.data.result
						_this.userId = data.newAppMentalHealthAssessmentEntity.userId
						_this.userName = data.newAppMentalHealthAssessmentEntity.userName
						_this.start_date = data.newAppMentalHealthAssessmentEntity.fillFormDate
						_this.editTid = data.newAppMentalHealthAssessmentEntity.tid
						_this.questionnaire.map((a)=>{
							data.newUserTopicsEntities.map((b)=>{ 
								if(a.id == b.titleId){
									a.adTopicsRepliesEntityList.map((c)=>{
										c.nid = b.id
										if(c.elections == b.userOption){
											c.checked = true
										}
									})
								}
							})
						})
					})
				}
			})
		},
		methods:{
			// 获取题目
			findByTopicsTypeAxios(){
				return new Promise((success,error)=>{
					this.$api.findByTopicsType('ids=17').then((res)=>{
						if(res){
							this.questionnaire = res.data.result['17'].adTopicsRepliesEntityList.map((a)=>{
								a.adTopicsRepliesEntityList = a.adTopicsRepliesEntityList.map((b)=>{b.checked = false;return b})
								return a
							})
							success(res.data.result)
						}else{
							error('')
						}
					})
				})
			},
			// 选答案
			answer(aitem,item) {
				if(this.selected){
					return;
				}
				const constArr = item.adTopicsRepliesEntityList.map((a) => {
					a.checked = false
					return a
				})
				aitem.checked = true			
			},
			// 保存
			showModalbtn(e) {
				const _this = this;
				if(this.isSave){
					uni.showToast({
						title:'该数据已生成报告，请返回重新添加',
						icon:'none'
					})
					return
				}
				if(!this.userId) {
					uni.showToast({
						title:'请选择会员',
						icon:'none'
					})
					return
				}
				if(!this.start_date) {
					uni.showToast({
						title:'请选择日期',
						icon:'none'
					})
					return
				}
				let appUserTopicsEntities = this.questionnaire.map((a)=>{
					let checkedArr = a.adTopicsRepliesEntityList.filter((b)=>{return b.checked})
					return {
						titleId:a.id,
						id:checkedArr.length > 0 && checkedArr[0].nid||a.adTopicsRepliesEntityList[0].nid,
						userOption:checkedArr.length > 0? checkedArr[0].elections : ''
					}
				})
				const data = {
					userId : this.userId,
					userName : this.userName,
					status: e,
					source: 3,
					upload: 3,
					fillFormDate:this.start_date,
					healthId: JSON.parse(localStorage.userInfo).id,
					tid: [17],
					appUserTopicsEntities:appUserTopicsEntities,
					appUserTopicsTitleEntity:{
						healthId:JSON.parse(localStorage.userInfo).id,
						userId:this.userId
					}
				}
				if(this.edit){
					// 编辑
					if(this.selected == 1){
						delete data.source
					}
					data.id = Number(this.editId)
					data.appUserTopicsTitleEntity.id = this.editTid
					this.$api.healthAssessmentUpdate(data).then((res)=>{
						if(res.data.returnCode == 200){
							if(e == 3){
								//申请评估
								_this.info = res.data.result
								uni.showLoading({title:'加载中'})
								setTimeout(()=>{
									_this.$refs.reportImgType2.toImg().then((base64)=>{
										_this.isSave = true
										var arr = base64.split(',')
										var mime = arr[0].match(/:(.*?);/)[1]
										var bstr = atob(arr[1]) 
										var nn = bstr.length 
										var u8arr = new Uint8Array(nn);
										while(nn--){
											u8arr[nn] = bstr.charCodeAt(nn);
										}
										var obj1 = new Blob([u8arr], {type:mime});
										_this.$api.healthAssessmentuploadWord({fileOne:obj1},res.data.result.id).then((ares) => {
											uni.hideLoading()
											if(JSON.parse(ares.data).returnCode == 200){
												window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+JSON.parse(ares.data).result.url
											}
										})
									})
								},1000)
							}else{
								uni.navigateTo({
									url:'/pages/quickly/healthStatus/navigation?current=2'
								})
							}
						}
					})
				}else{
					// 保存
					_this.$api.healthAssessmentAdd(data).then((res)=>{
						if(res.data.returnCode == 200){
							if(e == 3){
								_this.isSave = true
								//申请评估
								_this.info = res.data.result
								uni.showLoading({title:'加载中'})
								setTimeout(()=>{
									_this.$refs.reportImgType2.toImg().then((base64)=>{
										var arr = base64.split(',')
										var mime = arr[0].match(/:(.*?);/)[1]
										var bstr = atob(arr[1]) 
										var nn = bstr.length 
										var u8arr = new Uint8Array(nn);
										while(nn--){
											u8arr[nn] = bstr.charCodeAt(nn);
										}
										var obj1 = new Blob([u8arr], {type:mime});
										_this.$api.healthAssessmentuploadWord({fileOne:obj1},res.data.result.id).then((ares) => {
											uni.hideLoading()
											if(JSON.parse(ares.data).returnCode == 200){
												window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+JSON.parse(ares.data).result.url
											}
										})
									})
								},1000)
							}else{
								uni.navigateTo({
									url:'/pages/quickly/healthStatus/navigation?current=2'
								})
							}
						}
					})
				}
			},
			//关闭弹出框
			hidedialog(){
				this.dialog = false
			},
			//选择会员
			chooseUser(e){
				this.userId = e.userId;
				this.userName = e.userName;
			},
			// 日期
			bindDateChange(e) { 
				this.start_date = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
		}
	}
</script>


<style lang="scss" scoped>
@import '@/static/css/quickly/healthStatus/common.scss';
</style>